{% extends 'base.html' %}
{% load static %}

{% block title %}私信 - 本地有约{% endblock %}

{% block content %}
<div class="container py-4">
    <div class="row">
        <div class="col-lg-8 mx-auto">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h4 class="mb-0"><i class="fas fa-envelope me-2"></i>我的私信</h4>
                    <span class="badge bg-primary" id="unreadCount">
                        {{ conversations|length }} 个对话
                    </span>
                </div>
                <div class="card-body p-0">
                    <div id="conversations-container">
                        {% if conversations %}
                        <div class="list-group list-group-flush" id="conversations-list">
                            {% for conversation in conversations %}
                            <a href="{% url 'location:message_thread' conversation.user.id %}"
                               class="list-group-item list-group-item-action d-flex align-items-center py-3 conversation-item"
                               data-user-id="{{ conversation.user.id }}">
                                <div class="position-relative me-3">
                                    <img src="{{ conversation.user.avatar.url|default:'/static/images/default-avatar.jpg' }}"
                                         class="rounded-circle" width="50" height="50" alt="头像">
                                    {% if conversation.unread_count > 0 %}
                                    <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger unread-badge"
                                          id="unread-{{ conversation.user.id }}">
                                        {{ conversation.unread_count }}
                                    </span>
                                    {% endif %}
                                </div>

                                <div class="flex-grow-1">
                                    <div class="d-flex justify-content-between align-items-start mb-1">
                                        <h6 class="mb-0">{{ conversation.user.username }}</h6>
                                        <small class="text-muted last-message-time"
                                                id="time-{{ conversation.user.id }}">
                                            {{ conversation.last_message.created_at|timesince }}前
                                        </small>
                                    </div>

                                    <p class="text-muted mb-1 small text-truncate last-message-content"
                                       id="content-{{ conversation.user.id }}">
                                        {% if conversation.last_message.sender == user %}
                                        <span class="text-primary">我：</span>
                                        {% endif %}
                                        {{ conversation.last_message.content|truncatechars:50 }}
                                    </p>

                                    <div class="d-flex align-items-center">
                                        {% if conversation.user.profile.occupation %}
                                        <small class="text-muted me-3">
                                            <i class="fas fa-briefcase me-1"></i>{{ conversation.user.profile.occupation }}
                                        </small>
                                        {% endif %}
                                        <small class="text-muted">
                                            <i class="fas fa-comments me-1"></i>{{ conversation.user.received_messages.count }} 消息
                                        </small>
                                    </div>
                                </div>

                                <div class="ms-3">
                                    <i class="fas fa-chevron-right text-muted"></i>
                                </div>
                            </a>
                            {% endfor %}
                        </div>
                        {% else %}
                        <div class="text-center py-5" id="no-messages">
                            <i class="fas fa-envelope-open fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">暂无私信</h5>
                            <p class="text-muted">还没有人与您开始对话</p>
                            <a href="{% url 'location:community_home' %}" class="btn btn-primary">
                                <i class="fas fa-users me-2"></i>去社区看看
                            </a>
                        </div>
                        {% endif %}
                    </div>
                </div>
            </div>

            <!-- 推荐用户 -->
            <div class="card mt-4">
                <div class="card-header">
                    <h6 class="mb-0"><i class="fas fa-user-plus me-2"></i>推荐关注</h6>
                </div>
                <div class="card-body">
                    <div id="recommended-users-container">
                        <!-- 这里将通过AJAX加载推荐用户 -->
                        <div class="text-center py-3">
                            <div class="spinner-border spinner-border-sm text-primary me-2" role="status"></div>
                            <span class="text-muted">正在加载推荐用户...</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// 定时刷新消息
let refreshInterval;
const REFRESH_INTERVAL = 5000; // 5秒刷新一次

// 启动自动刷新
function startAutoRefresh() {
    refreshInterval = setInterval(refreshMessages, REFRESH_INTERVAL);
}

// 停止自动刷新
function stopAutoRefresh() {
    if (refreshInterval) {
        clearInterval(refreshInterval);
    }
}

// 刷新消息列表
async function refreshMessages() {
    try {
        const response = await fetch('/location/social/messages/conversations/json/', {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Content-Type': 'application/json',
            }
        });

        if (!response.ok) {
            throw new Error('网络请求失败');
        }

        const data = await response.json();

        if (data.success) {
            updateConversationsList(data.conversations);
        } else {
            console.error('刷新失败:', data.message);
        }
    } catch (error) {
        console.error('刷新消息失败:', error);
    }
}

// 更新对话列表
function updateConversationsList(conversations) {
    const container = document.getElementById('conversations-container');

    if (conversations.length === 0) {
        container.innerHTML = `
            <div class="text-center py-5" id="no-messages">
                <i class="fas fa-envelope-open fa-3x text-muted mb-3"></i>
                <h5 class="text-muted">暂无私信</h5>
                <p class="text-muted">还没有人与您开始对话</p>
                <a href="{% url 'location:community_home' %}" class="btn btn-primary">
                    <i class="fas fa-users me-2"></i>去社区看看
                </a>
            </div>
        `;
        return;
    }

    let html = '<div class="list-group list-group-flush" id="conversations-list">';

    conversations.forEach(conversation => {
        const unreadBadge = conversation.unread_count > 0 ?
            `<span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger unread-badge"
                   id="unread-${conversation.user.id}">${conversation.unread_count}</span>` : '';

        const lastMessagePrefix = conversation.last_message_sender_id === {{ user.id }} ?
            '<span class="text-primary">我：</span>' : '';

        html += `
            <a href="/location/social/messages/${conversation.user.id}/"
               class="list-group-item list-group-item-action d-flex align-items-center py-3 conversation-item"
               data-user-id="${conversation.user.id}">
                <div class="position-relative me-3">
                    <img src="${conversation.user.avatar_url}"
                         class="rounded-circle" width="50" height="50" alt="头像">
                    ${unreadBadge}
                </div>

                <div class="flex-grow-1">
                    <div class="d-flex justify-content-between align-items-start mb-1">
                        <h6 class="mb-0">${conversation.user.username}</h6>
                        <small class="text-muted last-message-time"
                                id="time-${conversation.user.id}">
                            ${conversation.last_message_time}前
                        </small>
                    </div>

                    <p class="text-muted mb-1 small text-truncate last-message-content"
                       id="content-${conversation.user.id}">
                        ${lastMessagePrefix}${conversation.last_message_content}
                    </p>

                    <div class="d-flex align-items-center">
                        ${conversation.user.occupation ?
                            `<small class="text-muted me-3">
                                <i class="fas fa-briefcase me-1"></i>${conversation.user.occupation}
                            </small>` : ''}
                        <small class="text-muted">
                            <i class="fas fa-comments me-1"></i>${conversation.message_count} 消息
                        </small>
                    </div>
                </div>

                <div class="ms-3">
                    <i class="fas fa-chevron-right text-muted"></i>
                </div>
            </a>
        `;
    });

    html += '</div>';
    container.innerHTML = html;

    // 更新对话数量
    document.getElementById('unreadCount').textContent = `${conversations.length} 个对话`;
}

// 开始对话
async function startConversation(userId) {
    try {
        const response = await fetch(`/location/social/messages/${userId}/`);
        if (response.ok) {
            window.location.href = `/location/social/messages/${userId}/`;
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

// 页面可见性变化处理
function handleVisibilityChange() {
    if (document.hidden) {
        // 页面不可见时停止自动刷新
        stopAutoRefresh();
    } else {
        // 页面可见时开始自动刷新，并立即刷新一次
        startAutoRefresh();
        refreshMessages();
    }
}

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    // 启动自动刷新
    startAutoRefresh();

    // 监听页面可见性变化
    document.addEventListener('visibilitychange', handleVisibilityChange);

    // 页面卸载时停止自动刷新
    window.addEventListener('beforeunload', stopAutoRefresh);
});

// 获取CSRF令牌
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
// 获取推荐用户
async function loadRecommendedUsers() {
    try {
        const response = await fetch('/location/api/recommended-users/', {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Content-Type': 'application/json',
            }
        });

        if (!response.ok) {
            throw new Error('网络请求失败');
        }

        const data = await response.json();

        if (data.success) {
            updateRecommendedUsers(data.users);
        } else {
            console.error('加载推荐用户失败:', data.message);
            showRecommendedUsersError();
        }
    } catch (error) {
        console.error('加载推荐用户失败:', error);
        showRecommendedUsersError();
    }
}

// 更新推荐用户列表
function updateRecommendedUsers(users) {
    const container = document.getElementById('recommended-users-container');

    if (users.length === 0) {
        container.innerHTML = `
            <div class="text-center py-3">
                <i class="fas fa-users fa-2x text-muted mb-2"></i>
                <p class="text-muted mb-0">暂无推荐用户</p>
                <small class="text-muted">去社区发帖，让更多人认识你吧！</small>
            </div>
        `;
        return;
    }

    let html = '<div class="row">';

    users.forEach(user => {
        html += `
            <div class="col-md-6 mb-3">
                <div class="d-flex align-items-center">
                    <img src="${user.avatar_url}"
                         class="rounded-circle me-3" width="45" height="45" alt="${user.username}的头像">
                    <div class="flex-grow-1">
                        <h6 class="mb-1">${user.username}</h6>
                        <small class="text-muted">
                            ${user.posts_count} 帖子 ·
                            ${user.events_count} 活动
                        </small>
                        ${user.common_interests ? `
                        <div class="mt-1">
                            <small class="text-primary">
                                <i class="fas fa-tags me-1"></i>共同兴趣：${user.common_interests}
                            </small>
                        </div>
                        ` : ''}
                    </div>
                    <button class="btn btn-sm btn-outline-primary" onclick="startConversation(${user.id})">
                        发消息
                    </button>
                </div>
            </div>
        `;
    });

    html += '</div>';
    container.innerHTML = html;
}

// 显示推荐用户加载错误
function showRecommendedUsersError() {
    const container = document.getElementById('recommended-users-container');
    container.innerHTML = `
        <div class="text-center py-3">
            <i class="fas fa-exclamation-triangle text-warning fa-2x mb-2"></i>
            <p class="text-muted mb-2">加载推荐用户失败</p>
            <button class="btn btn-sm btn-outline-primary" onclick="loadRecommendedUsers()">
                <i class="fas fa-redo me-1"></i>重新加载
            </button>
        </div>
    `;
}

// 页面加载完成后获取推荐用户
document.addEventListener('DOMContentLoaded', function() {
    loadRecommendedUsers();
});
</script>

<style>
.list-group-item {
    border: none;
    transition: background-color 0.2s ease;
}

.list-group-item:hover {
    background-color: #f8f9fa;
}

.list-group-item:not(:last-child) {
    border-bottom: 1px solid #e9ecef !important;
}
</style>
{% endblock %}